<?php

declare(strict_types=1);

namespace App\Common\Service\Affiliate;

use App\Common\Helpers\UrlHelper;

/**
 * https://jos.jd.com/commondoc?listId=306
 */
class JdService extends AbstractAffiliateService
{
    public function getAuthUrl(array $params): string
    {
        $domain = $this->getDomain();
        $callBackUrl = hyperf_url("callback/jdLoginCallback/uid/{uid}/main_uid/{main_uid}/suc_jump/{suc_jump}/type/{type}",[
            'uid' => $params['uid'],
            'main_uid' => $params['main_uid'],
            'suc_jump' => urlencode($params['url']),
            'type' => $params['type'],
        ],$domain);
        $urls = 'https://router.wikeyun.cn/api/oauth/jd?serviceType=2&redirect_uri=' . urlencode($callBackUrl);
        return $urls;
    }

    public function getAppKeyName(): string
    {
        return 'jd_app_key';
    }

    public function getAppSecretName(): string
    {
        return 'jd_app_secret';
    }


    /**
     * 通过code获取access_token
     * @param $code
     * @return false|mixed
     */
    public function getAccessToken($code): mixed
    {
        $config = $this->getAppKeyAndSecret();
        $appKey = $config['appKey'];
        $appSecret = $config['appSecret'];
        $url = "https://open-oauth.jd.com/oauth2/access_token";

        return $this->get($url,[
            'app_key' => $appKey,
            'app_secret' => $appSecret,
            'grant_type' => 'authorization_code',
            'code' => $code,
        ]);
    }

    /**
     * 刷新token
     * @param string $refresh_token
     * @return false|mixed
     */
    public function refreshToken(string $refresh_token): mixed
    {
        $config = $this->getAppKeyAndSecret();
        $appKey = $config['appKey'];
        $appSecret = $config['appSecret'];
        $url = "https://open-oauth.jd.com/oauth2/access_token";

        return $this->get($url,[
            'app_key' => $appKey,
            'app_secret' => $appSecret,
            'grant_type' => 'refresh_token',
            'refresh_token' => $refresh_token,
        ]);
    }
}